package com.zgxt.demo.controller;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.zgxt.demo.Dao.UserDao;
import com.zgxt.demo.entity.Role;
import com.zgxt.demo.entity.User;
import com.zgxt.demo.service.UserService;
import com.zgxt.demo.util.UserHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {


    @Autowired
    private Producer producer;

    @Autowired
    private UserService userService;

    //Redis对象
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    String click;


    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpeg");
        //验证码内容
        String text = producer.createText();
        //得到验证码图片
        BufferedImage image = producer.createImage(text);
        click= IdUtil.simpleUUID();;
        //把文本促存到Redis中 设置过期时间60秒
        stringRedisTemplate.opsForValue().set(click,text,60, TimeUnit.SECONDS);
        //把图片写到返回的远程对象中
        ServletOutputStream out=response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        IOUtils.closeQuietly(out);
    }

    @GetMapping("/sseintoken")
    public String sseintoken()  {
        return click;
    }

    @GetMapping("/tokenNot")
    public String tokenNot(){
        UserDao userDao= UserHolder.getUserDao();
        if (userDao.getUserId()>0)
            return "token存在";
        return "请重新登录";
    }

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String password, @RequestParam Integer role_id,@RequestParam String captcha,@RequestParam String sseintoken) {
        //声明返回对象
        JSONObject _outPut = new JSONObject();

        String kaptcha = stringRedisTemplate.opsForValue().get(sseintoken);
        if (captcha==null || captcha.isEmpty()){
            _outPut.put("code", 500);
            _outPut.put("msg","验证码不能为空");
            return _outPut.toJSONString();
        }

        if (!Objects.equals(kaptcha, captcha)){
            _outPut.put("code", 500);
            _outPut.put("msg","验证码错误");
            return _outPut.toJSONString();
        }
        User user = userService.login(account, password, role_id);
        if (user==null){
            _outPut.put("code", 500);
            _outPut.put("msg","地址或者密码错误");
            return _outPut.toJSONString();
        }
        //生成随机toKen，作为登录令牌
        String toKen= IdUtil.simpleUUID();
        _outPut.put("code",200);
        _outPut.put("data",user.getName());
        _outPut.put("toKen",toKen);
        Map<String,Object> objectMap=new HashMap<>();
        objectMap.put("userId",user.getId());
        objectMap.put("address",user.getAddress());
        //把用户ID和区块链地址保存到Redis中
        Map<String,Object> map = BeanUtil.beanToMap(objectMap,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)-> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll("Food:token:" + toKen,map);
        //设置过期时间
        stringRedisTemplate.expire("Food:token:" + toKen,30L,TimeUnit.MINUTES);
        return _outPut.toJSONString();
    }

    @GetMapping("/role")
    public String RoleList(){
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        _outPut.put("code",200);
        _outPut.put("data",userService.RoleList());
        return _outPut.toJSONString();
    }

    @GetMapping("/registerId")
    public String registerId(){
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        _outPut.put("code",200);
        _outPut.put("data",IdUtil.simpleUUID());
        return _outPut.toJSONString();
    }

    @PostMapping("/register")
    public String register(@RequestParam String name, @RequestParam String address, @RequestParam String password) {
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        Integer tid= userService.register(name,address,password);
        if (tid==1){
            _outPut.put("code",200);
            _outPut.put("msg","注册成功");
        }
        if (tid==2){
            _outPut.put("code",500);
            _outPut.put("msg","账号已经存在");
        }
        return _outPut.toJSONString();
    }

    @PostMapping("/forget")
    public String forget(@RequestParam String address, @RequestParam String password,@RequestParam String confirm_password) {
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        Integer tid=userService.forget(address,password,confirm_password);
        if (tid==2){
            _outPut.put("code",500);
            _outPut.put("msg","两次密码请保持一样");
        }
        if (tid==0){
            _outPut.put("code",500);
            _outPut.put("msg","参数问题");
        }
        if (tid==3){
            _outPut.put("code",500);
            _outPut.put("msg","新密码与原先密码不能相同");
        }
        if (tid==1){
            _outPut.put("code",200);
            _outPut.put("msg","修改成功");
        }
        return _outPut.toJSONString();
    }

    @PostMapping("/query_users")
    public Map<String,Object> queryusers(@RequestParam("page") Integer pageIndex, @RequestParam Integer limit, String name) {
        return userService.QueryUser(pageIndex*limit,limit,name);
    }

    @PostMapping("/delete_user")
    public String deleteusers(@RequestParam String ids) {
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        Integer tid=userService.deleteUser(ids);
        if (tid>0){
            _outPut.put("code",200);
            _outPut.put("msg","删除成功");
        }else {
            _outPut.put("code",500);
            _outPut.put("msg","删除失败");
        }
        return _outPut.toJSONString();
    }

    @PostMapping("/update_user")
    public String updateUser(@RequestParam Integer id,@RequestParam String name,@RequestParam String password) {
        //声明返回对象
        JSONObject _outPut = new JSONObject();
        Integer tid=userService.updateUser(id,name,password);
        if (tid==1){
            _outPut.put("code",200);
            _outPut.put("msg","更改成功");
        }else {
            _outPut.put("code",500);
            _outPut.put("msg","更改失败");
        }
        return _outPut.toJSONString();
    }
}
